<?php

namespace App\Helpers;

use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use PhpParser\Node\Expr\Array_;

trait ApiResponse
{
    /**
     * 成功分页返回
     * @param $page
     */
    protected function successPaginate($page)
    {
        return $this->paginate($page);
    }

    private function paginate($page)
    {
        if ($page instanceof LengthAwarePaginator){
            return [
                'total'  => $page->total(),
                'page'   => $page->currentPage(),
                'limit'  => $page->perPage(),
                'pages'  => $page->lastPage(),
                'list'   => $page->items()
            ];
        }
        if ($page instanceof Collection){
            $page = $page->toArray();
        }
        if (!is_array($page)){
            return $page;
        }
        $total = count($page);
        return [
            'total'  => $total,
            'page'   => 1,
            'limit'  => $total,
            'pages'  => 1,
            'list'   => $page
        ];
    }


}
